package cn.sciento.starter.social.core.configuration;

import cn.sciento.starter.social.core.security.SocialFailureHandler;
import cn.sciento.starter.social.core.security.SocialSuccessHandler;
import cn.sciento.starter.social.core.security.SpringSocialConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;

@Order(-100)
@EnableConfigurationProperties({SocialProperties.class})
@Configuration
public class SocialWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
  @Autowired
  private SocialProperties properties;
  
  @Autowired(required = false)
  private SocialSuccessHandler socialSuccessHandler;
  
  @Autowired(required = false)
  private SocialFailureHandler socialFailureHandler;
  
  protected void configure(HttpSecurity http) throws Exception {
    ((HttpSecurity)((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)http
      .antMatcher(this.properties.getProcessUrl() + "/**")
      .authorizeRequests()
      .anyRequest())
      .permitAll()
      .and())
      .csrf()
      .disable();
    SpringSocialConfigurer configurer = new SpringSocialConfigurer();
    configurer
      .bindUrl(this.properties.getBindUrl())
      .setAttemptBind(this.properties.isAttemptBind())
      .setEnableHttps(this.properties.isEnableHttps())
      .setFilterProcessesUrl(this.properties.getProcessUrl());
    if (this.socialSuccessHandler != null)
      configurer.successHandler(this.socialSuccessHandler); 
    if (this.socialFailureHandler != null)
      configurer.failureHandler(this.socialFailureHandler); 
    http.apply((SecurityConfigurerAdapter)configurer);
  }
}
